import {ActionSheetController} from 'ionic-angular';
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {DomSanitizer} from "@angular/platform-browser";
import {NativeProvider} from "@providers/natives/native";
import {FileObj} from "@common/FileObj";

/**
 * 自定义添加/预览图片组件
 * @description
 * @example <page-select-pic [(fileObjList)]="fileObjList"></page-select-pic>
 * @example <page-select-pic [max]="6" [allowAdd]="true" [allowDelete]="true" [(fileObjList)]="fileObjList"></page-select-pic>
 */
@Component({
  selector: 'select-pic-native',
  templateUrl: 'select-pic-native.html',
})
export class SelectPicNativeComponent {
  @Input() max: number = 4;  //最多可选择多少张图片，默认为4张

  @Input() allowAdd: boolean = true;  //是否允许新增

  @Input() allowDelete: boolean = true;  //是否允许删除

  @Input() fileObjList: FileObj[] = [];   //图片列表,与fileObjListChange形成双向数据绑定

  @Input() mode: string = 'camera';//模式选择：camera--照相  image--从图库选择  all--既可以拍照又可以从图库选择
  @Output() fileObjListChange = new EventEmitter<any>();
  @Output() addImage = new EventEmitter<any>();
  @Output() delImage = new EventEmitter<any>();

  constructor(private actionSheetCtrl: ActionSheetController, private native: NativeProvider,
              public sanitizer: DomSanitizer) {
  }

  addPicture() {
    if (this.mode == 'camera') {
      this.startCamera();
    } else if (this.mode == 'image') {
      this.openImgPicker();
    } else if (this.mode == 'all') {
      this.useASComponent();
    }
  }

  // 使用ionic中的ActionSheet组件
  useASComponent() {
    let actionSheet = this.actionSheetCtrl.create({
      title: '选择',
      buttons: [
        {
          text: '拍照',
          handler: () => {
            this.startCamera();
          }
        },
        {
          text: '从手机相册选择',
          handler: () => {
            this.openImgPicker();
          }
        },
        {
          text: '取消',
          role: 'cancel',
          handler: () => {

          }
        }
      ]
    });
    actionSheet.present();
  }

  // 启动拍照功能
  startCamera() {
    // 调用相机时传入的参数
    let cameraOpt = {
      quality: 20,
      destinationType: 1, // Camera.DestinationType.FILE_URI,
      // sourceType: 1, // Camera.PictureSourceType.CAMERA,
      encodingType: 0, // Camera.EncodingType.JPEG,
      mediaType: 0, // Camera.MediaType.PICTURE,
      targetWidth: 800,//缩放图像的宽度（像素）
      targetHeight: 800,//缩放图像的高度（像素）
      allowEdit: false,
      correctOrientation: true,
      saveToPhotoAlbum: false
    };
    this.native.getPictureByCamera(cameraOpt).subscribe(imageData => {
      let fileObj = <FileObj>{'origPath': imageData, 'thumbPath': imageData};
      this.fileObjList.push(fileObj);
      this.addImage.emit(fileObj);
      this.fileObjListChange.emit(this.fileObjList);
    });
  }

  // 打开手机相册
  openImgPicker() {
    // 调用相册时传入的参数
    let imagePickerOpt = {
      destinationType: 1,
      // maximumImagesCount: (this.max - this.fileObjList.length),//选择一张图片
      width: 800,
      height: 800,
      quality: 20
    };
    this.native.getMultiplePicture(imagePickerOpt).subscribe(results => {
      for (let img of results) {
        let fileObj = <FileObj>{'origPath': img, 'thumbPath': img};
        this.fileObjList.push(fileObj);
        this.addImage.emit(fileObj);
        this.fileObjListChange.emit(this.fileObjList);
      }
    });
  }

  deletePicture(i) {//删除照片
    if (!this.allowDelete) {
      return;
    }
    let that = this;
    that.actionSheetCtrl.create({
      buttons: [
        {
          text: '删除',
          role: 'destructive',
          handler: () => {
            this.delImage.emit(that.fileObjList[i]);
            that.fileObjList.splice(i, 1);
          }
        },
        {
          text: '取消',
          role: 'cancel'
        }
      ]
    }).present();
  }

  viewerPicture(index) {//照片预览
    let current = '';
    for (let i = 0, len = this.fileObjList.length; i < len; i++) {
      let origPath = this.fileObjList[i].origPath;
      if (i == index) {
        current = origPath;
      }
    }
    this.native.previewImage(current);
  }
}
